"""控制台UI类"""
from typing import Dict, Callable
from chat_api import ChatAPI, ChatAPIError


class ConsoleUI:
    def __init__(self):
        self.chat_api = ChatAPI()
        self.stream_mode = True
        self.commands = {
            'exit': self._handle_exit,
            'quit': self._handle_exit,
            'stream': self._handle_stream,
            'new': self._handle_new_conversation,
            'id': self._handle_show_id,
            'help': self._handle_help
        }

    def _handle_exit(self, *args) -> bool:
        """处理退出命令"""
        print("\n感谢使用！再见！")
        return False

    def _handle_stream(self, *args) -> bool:
        """处理流式输出切换命令"""
        self.stream_mode = not self.stream_mode
        print(f"\n流式输出模式已{'开启' if self.stream_mode else '关闭'}")
        return True

    def _handle_new_conversation(self, *args) -> bool:
        """处理新会话命令"""
        self.chat_api.start_new_conversation()
        print("\n已开始新的对话")
        return True

    def _handle_show_id(self, *args) -> bool:
        """处理显示会话ID命令"""
        conversation_id = self.chat_api.get_conversation_id()
        if conversation_id:
            print(f"\n当前会话ID: {conversation_id}")
        else:
            print("\n当前是新会话，还没有会话ID")
        return True

    def _handle_help(self, *args) -> bool:
        """显示帮助信息"""
        print("\n=== 命令帮助 ===")
        print("exit/quit - 退出程序")
        print("stream    - 切换流式输出（当前" + ("开启" if self.stream_mode else "关闭") + "）")
        print("new      - 开始新的对话")
        print("id       - 查看当前会话ID")
        print("help     - 显示此帮助信息")
        print("\n直接输入文本开始对话")
        return True

    def process_message(self, message: str) -> None:
        """处理用户输入的消息"""
        if not message.strip():
            print("\n请输入有效的消息内容。")
            return

        try:
            self.chat_api.chat_message(message, stream=self.stream_mode)
        except ChatAPIError as e:
            print(f"\n对话出错: {str(e)}")
        except Exception as e:
            print(f"\n发生未知错误: {str(e)}")

    def run(self) -> None:
        """运行控制台界面"""
        print("\n=== Dify AI 聊天助手 ===")
        print("输入 'help' 获取命令帮助")

        running = True
        while running:
            try:
                message = input("\n您: ").strip().lower()

                # 处理命令
                if message in self.commands:
                    running = self.commands[message]()
                    continue

                # 处理普通消息
                self.process_message(message)

            except KeyboardInterrupt:
                print("\n\n程序已被用户中断。再见！")
                break
            except Exception as e:
                print(f"\n发生错误: {str(e)}")
                print("请重试或输入 'exit' 退出程序。")
